<template>
  <view class="category-page">
    <!-- 顶部搜索栏 -->
    <view class="search-bar">
      <view class="input-wrap">
        <text class="icon">🔍</text>
        <input class="input" placeholder="搜索陪爬员..." confirm-type="search" @confirm="onSearch"/>
      </view>
      <view class="more" @tap="onMore">···</view>
    </view>

    <!-- 筛选条 -->
    <view class="filter-row">
      <text class="filter-text">当前筛选：全部陪爬员</text>
      <text class="filter-action" @tap="onFilter">清除筛选</text>
    </view>

    <view class="layout">
      <!-- 左侧分类 -->
      <view class="side">
        <view v-for="(item,i) in categories" :key="i" :class="['side-item', {active: i===activeCat}]" @tap="onSelectCategory(i)">{{ item }}</view>
      </view>

      <!-- 右侧内容 -->
      <view class="content">
        <view class="section-title-row">
          <text class="section-title">热门陪爬员</text>
        </view>
        <view v-if="loading" class="loading">加载中...</view>
        <view v-else-if="error" class="error">{{ error }}</view>
        <view v-else>
          <view v-if="!coaches.length" class="loading">暂无数据</view>
          <view v-else class="cards">
            <view class="card" v-for="(coach, idx) in coaches" :key="coach.id" :data-id="coach.id" @tap="goDetail">
              <view class="card-cover">
                <image class="img" :src="coach.img" mode="aspectFill" />
                <text class="badge" :class="coach.statusType">{{ coach.statusText }}</text>
              </view>
              <view class="card-body">
                <view class="row">
                  <text class="name">{{ coach.name }}</text>
                  <text class="rate">{{ Number(coach.star || 0).toFixed(1) }}★</text>
                </view>
                <text class="bio" v-if="coach.bio">{{ coach.bio }}</text>
                <view class="row-bottom">
                  <text class="price">¥{{ Number(coach.price || 0).toFixed(2) }}/小时</text>
                  <button class="btn" size="mini" @tap="book(coach)">预约</button>
                </view>
                <text class="meta">入驻：{{ formatDate(coach.createTime) }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部分页条 -->
    <view v-if="total>0" class="pagination-bar">
      <text class="pg-info">共{{ total }}条</text>
      <view class="pg-controls">
        <button class="pg-btn" size="mini" :disabled="pageNum<=1" @tap="gotoPage(pageNum-1)">上一页</button>
        <text class="pg-current">{{ pageNum }}</text>
        <text>/</text>
        <text class="pg-total">{{ Math.max(1, Math.ceil(total / pageSize)) }}</text>
        <button class="pg-btn" size="mini" :disabled="pageNum>=Math.ceil(total/pageSize)" @tap="gotoPage(pageNum+1)">下一页</button>
      </view>
      <view class="pg-sizes">
        <text v-for="s in pageSizes" :key="s" :class="['pg-size', {active: pageSize===s}]" @tap="changePageSize(s)">{{ s }}条/页</text>
      </view>
    </view>

	<emergency-sos bottom="160" right="24" />
	<custom-tabbar :active="1" />
  </view>
  
</template>

<script>
import CustomTabbar from '@/components/custom-tabbar/custom-tabbar.vue'
import EmergencySOS from '@/components/emergency-sos/emergency-sos.vue'
import { listCoaches } from '@/api/coach'
export default {
  components: { CustomTabbar, EmergencySOS },
  data() {
    return {
      activeCat: 0,
      categories: ['默认分类','评分优先','价格优先'],
      coaches: [],
      loading: false,
      error: '',
      searchKeyword: '',
      pageNum: 1,
      pageSize: 10,
      finished: false,
      total: 0,
      pageSizes: [10,20,50]
    }
  },
  onLoad() { this.resetAndFetch() },
  methods: {
    async fetchCoaches() {
      this.loading = true
      this.error = ''
      try {
        const payload = { 
          keyword: this.searchKeyword, 
          pageNum: this.pageNum, 
          pageSize: this.pageSize,
          price: this.activeCat === 2 ? '1' : '',
          score: this.activeCat === 1 ? '1' : ''
        }
        const res = await listCoaches(payload)
        let list = []
        if (Array.isArray(res.data)) list = res.data
        else if (res.data && Array.isArray(res.data.rows)) list = res.data.rows
        else if (Array.isArray(res.rows)) list = res.rows
        else if (Array.isArray(res.list)) list = res.list
        const mapped = (list || []).map(this.mapCoach)
        // 分页模式：每次翻页均替换当前页数据
        this.coaches = mapped
        const total = (res.data && res.data.total) || res.total
        if (total != null) {
          this.total = Number(total)
          const totalPages = Math.max(1, Math.ceil(this.total / this.pageSize))
          this.finished = this.pageNum >= totalPages
        } else {
          this.finished = !mapped.length || mapped.length < this.pageSize
        }
      } catch (err) {
        this.error = (err && err.msg) || '加载失败，请重试'
      } finally {
        this.loading = false
      }
    },
    resetAndFetch(){
      this.pageNum = 1
      this.finished = false
      this.fetchCoaches()
    },
    // 保留按需：如需上拉加载，可恢复此函数并添加 onReachBottom 钩子
    gotoPage(p){
      const max = Math.max(1, Math.ceil(this.total / this.pageSize))
      if (p < 1 || p > max) return
      this.pageNum = p
      this.fetchCoaches()
    },
    changePageSize(s){
      if (this.pageSize === s) return
      this.pageSize = s
      this.pageNum = 1
      this.fetchCoaches()
    },
    onSelectCategory(i){
      this.activeCat = i
      this.resetAndFetch()
    },
    mapCoach(raw) {
      // 列表接口已过滤只返回已通过的陪爬员；
      // 若后端未返回状态，则默认按已认证展示，避免错误显示“待审核”。
      const statusVal = this.firstDefined(raw.qualification_status, raw.qualificationStatus, '1')
      const status = String(statusVal)
      let statusText = '已认证'
      let statusType = 'status-success'
      if (status === '0') { statusText = '待审核'; statusType = 'status-pending' }
      else if (status === '2') { statusText = '已拒绝'; statusType = 'status-reject' }
      return {
        id: this.firstDefined(raw.id, raw.climberId, raw.companionId, raw.coachId, raw.userId, raw.user_id, raw.uuid),
        name: raw.name || '未命名',
        star: Number(raw.score || 0),
        price: Number(raw.price || 0),
        bio: raw.bio || '',
        createTime: raw.create_time || raw.createTime || '',
        img: raw.img || raw.avatar || raw.photoUrl || raw.imageUrl || '/static/project/2025-10-14_110352_756.png',
        statusText,
        statusType,
        original: raw
      }
    },
    firstDefined() {
      for (let i = 0; i < arguments.length; i++) {
        const v = arguments[i]
        if (v !== undefined && v !== null) return v
      }
      return undefined
    },
    formatDate(val){
      if (!val) return ''
      // 兼容时间戳 / 字符串
      const d = typeof val === 'number' ? new Date(val) : new Date(String(val).replace(/-/g,'/'))
      if (isNaN(d.getTime())) return String(val)
      const pad = n => (n<10?('0'+n):n)
      return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}`
    },
    onSearch(e){
      this.searchKeyword = (e && e.detail && e.detail.value) || ''
      this.resetAndFetch()
    },
    onMore(){},
    onFilter(){
      this.searchKeyword = ''
      this.activeCat = 0
      this.resetAndFetch()
    },
    book(item){ this.$modal && this.$modal.showToast('已预约：' + item.name) }
    ,goDetail(e){
      const id = (e && e.currentTarget && e.currentTarget.dataset && e.currentTarget.dataset.id)
      if (!id) {
        this.$modal && this.$modal.showToast('缺少ID，无法打开详情')
        return
      }
      uni.navigateTo({
        url: `/pages/work/detail?id=${id}`,
        fail: (e) => {
          console.error('navigateTo fail', e)
          this.$modal && this.$modal.showToast('跳转失败：页面未注册或路径不对')
        }
      })
    }
  }
}
</script>

<style scoped>
.category-page { padding: 16rpx 16rpx 120rpx 16rpx; }
.search-bar { display: flex; align-items: center; justify-content: space-between; }
.input-wrap { flex: 1; display: flex; align-items: center; background: #f5f6f7; border-radius: 12rpx; padding: 12rpx 16rpx; }
.input { flex: 1; padding-left: 12rpx; }
.more { margin-left: 16rpx; color: #111; }
.filter-row { display: flex; align-items: center; justify-content: space-between; margin: 16rpx 0; font-size: 24rpx; color: #6b7280; }
.filter-action { color: #0ea5a5; }

.layout { display: flex; }
.side { width: 160rpx; }
.side-item { padding: 20rpx 12rpx; color: #6b7280; border-left: 6rpx solid transparent; }
.side-item.active { color: #111827; background: #f7fafc; border-left-color: #0ea5a5; font-weight: 600; }
.content { flex: 1; padding-left: 16rpx; }
.section-title-row { display:flex; align-items:center; justify-content: space-between; margin-bottom: 12rpx; }
.section-title { font-size: 28rpx; font-weight: 700; }
.add { color: #0ea5a5; }
.cards { display: grid; grid-template-columns: repeat(2, 1fr); gap: 16rpx; }
.card { background: #fff; border-radius: 16rpx; overflow: hidden; box-shadow: 0 6rpx 20rpx rgba(0,0,0,.04); }
.card-cover { position: relative; height: 220rpx; }
.img { width: 100%; height: 100%; }
.badge { position: absolute; top: 12rpx; right: 12rpx; background: #0ea5a5; color: #fff; font-size: 20rpx; padding: 4rpx 10rpx; border-radius: 20rpx; }
.card-body { padding: 12rpx; }
.row { display: flex; align-items: center; justify-content: space-between; }
.name { font-size: 26rpx; font-weight: 700; }
.rate { color: #f59e0b; font-size: 22rpx; }
.desc { display:block; margin: 6rpx 0 10rpx; color:#6b7280; font-size: 22rpx; }
.row-bottom { display:flex; align-items:center; justify-content: space-between; }
.price { color: #0ea5a5; font-weight: 700; }
.btn { background: #0ea5a5; color: #fff; border: none; padding: 0 16rpx; }
.loading { padding: 24rpx; color: #6b7280; }
.error { padding: 24rpx; color: #ef4444; }
.bio { display:block; margin: 8rpx 0 10rpx; color:#4b5563; font-size: 22rpx; line-height: 1.4; }
.meta { display:block; margin-top: 8rpx; color:#9ca3af; font-size: 20rpx; }
.status-success { background:#10b981; }
.status-pending { background:#f59e0b; }
.status-reject { background:#ef4444; }
.pager { text-align:center; color:#9ca3af; padding: 16rpx 0; }
.pagination { display:flex; align-items:center; justify-content: space-between; padding: 12rpx 0; color:#6b7280; }
.pg-info { font-size: 22rpx; }
.pg-sizes { display:flex; gap: 8rpx; }
.pg-size { background:#f3f4f6; padding: 6rpx 12rpx; border-radius: 999rpx; }
.pg-size.active { background:#ecfeff; color:#0ea5a5; }
.pg-controls { display:flex; align-items:center; gap: 8rpx; }
.pg-btn { background:#f3f4f6; color:#374151; border:none; }
.pg-current { min-width: 32rpx; text-align:center; }
.pg-total { color:#9ca3af; }

.pagination-bar { display:flex; align-items:center; justify-content: space-between; padding: 12rpx 8rpx 20rpx 8rpx; }
</style>
